
"""
It supports to look into the BitMap with a simple way
"""

__version__ = '1.1'

__aof__ = ('Bitmap Decoder', 'BMP')
__extension__ = (('BitMap Files', ('*.bmp',)),)


class _BitmapDecoder:  # pylint: disable=W0232
    def Execute(self, source, target, notify, **kws):  # pylint: disable=W0613
        entry = target.getEntry()
        start = kws.get('start', 0)

        data_offset, header_size, data_size = (0, 0, 0)
        # BitMap Header
        _HEADER = (
            ('Identifier', 2, 'value,verify', {'verified': 0x4d42}),
            ('File Size', 4, 'decimal'),
            ('Reserved', 4),
            ('Data Offset', 4, 'value,export'),
            ('Header Size', 4, 'decimal,export'),
            ('Width', 4, 'decimal'),
            ('Height', 4, 'decimal'),
            ('Planes', 2, 'value'),
            ('BitPerPixel', 2, 'decimal'),  # BPP
            ('Compression', 4, 'value'),
            ('Data Size', 4, 'decimal,export'),
            ('HResolution', 4, 'value'),
            ('VResolution', 4, 'value'),
            ('Colors', 4, 'value')
        )

        ret, objectp, _, _, exported = target.parse(
            'Header', _HEADER, afile=source, start=start)
        if ret:
            data_offset, header_size, data_size = exported
            entry.append(objectp)

        # Palette
        if ret and data_offset > header_size:
            palette = (data_offset - header_size) / 4
            _PALETTE = (
                ('ColorImportant', 4, 'value'),
                ('Color ', 4, 'value,recursive', {
                    'repeat': palette - 1,
                    'subdescriptor': (
                        ('Blue', 1, 'value'),
                        ('Green', 1, 'value'),
                        ('Red', 1, 'value'))
                }))

            ret, objectp, _, _, _ = target.parse(
                'Palette', _PALETTE, afile=source, start=start + header_size)
            if ret:
                entry.append(objectp)

        # Data
        if ret:
            objectp = target.newItemObject(
                'Data', '',
                target.newFieldObject(start + data_offset, data_size))
            entry.append(objectp)

        return ret


def fmtService():
    return _BitmapDecoder, 'picture'
